package com.zhitan.ems.app.iot.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhitan.ems.app.iot.entity.DeviceEntity;
import com.zhitan.ems.app.iot.enums.DEVICE_ONLINE_STATUS_ENUM;
import com.zhitan.ems.app.iot.mapper.DeviceMapper;
import com.zhitan.ems.app.iot.service.DeviceService;
import com.zhitan.ems.app.stat.vo.StatisticsPieVO;
import com.zhitan.ems.framework.core.mp.base.BaseServiceImpl;
import com.zhitan.ems.framework.core.vo.VQueryKit;

@Service
public class DeviceServiceImpl extends BaseServiceImpl<DeviceMapper, DeviceEntity> implements DeviceService {
	@Override
	public Map<String, Object> getOnlineStatusStatistics(Map<String, Object> params) {
		Map<String, Object> result = new HashMap<String, Object>();
		QueryWrapper<DeviceEntity> queryWrapper = VQueryKit.getQueryWrapperByMap(params,
				Arrays.asList("name", "deviceName"), DeviceEntity.class);
		// 查询最近一个月的报警记录，按处理状态分组统计
		queryWrapper.select("online_state, COUNT(*) as count");
		queryWrapper.groupBy("online_state");
		List<Map<String, Object>> statusStats = this.listMaps(queryWrapper);
		List<StatisticsPieVO> listStats = new ArrayList<StatisticsPieVO>();
		// 计算总报警数量
		int total = 0;
		for (Map<String, Object> stat : statusStats) {
			Integer onlineState = (Integer) stat.get("online_state");
			Long count = (Long) stat.get("count");
			if (count != null) {
				total += count.intValue();
			}
			StatisticsPieVO item = new StatisticsPieVO();
			item.setCount(count);
			item.setState(onlineState);
			item.setName(DEVICE_ONLINE_STATUS_ENUM.findByState(onlineState).getName());
			listStats.add(item);
		}
		// 计算各等级报警占比
		for (StatisticsPieVO stat : listStats) {
			Long count = stat.getCount();
			if (count != null) {
				double percentage = total > 0 ? (count.doubleValue() / total) * 100 : 0.0;
				stat.setPercentage(String.format("%.2f%%", percentage));
			}
		}
		// 将结果放入Map
		result.put("stats", listStats);
		result.put("total", total);
		return result;
	}
	@Override
	public DeviceEntity getDeviceByDeviceCode(String deviceCode) {
		if(deviceCode==null) {
			return null;
		}
		QueryWrapper<DeviceEntity> queryWrapper =new QueryWrapper<DeviceEntity>();
		queryWrapper.eq("device_code", deviceCode);
		return this.getOne(queryWrapper);
	}
}